package com.secondhand.project.service.impl;

import cn.hutool.core.date.DateUtil;
import com.secondhand.project.domain.Comment;
import com.secondhand.project.mapper.CommentMapper;
import com.secondhand.project.service.ICommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class CommentServiceImpl implements ICommentService {
    @Autowired
    private CommentMapper commentMapper;

    @Override
    public List<Comment> selectTree(Comment comment) {
        List<Comment> rootList = commentMapper.selectRoot(comment);
        for (Comment root : rootList) {
            Long rootId = root.getRootId();
            List<Comment> children = commentMapper.selectByRootId(rootId);
            root.setChildren(children);
        }
        return rootList;
    }

    @Override
    public Long selectCount(Comment comment) {
        return commentMapper.selectCount(comment);
    }

    @Override
    public Comment selectCommentById(Long id) {
        return commentMapper.selectCommentById(id);
    }

    @Override
    public List<Comment> selectCommentList(Comment comment) {
        return commentMapper.selectCommentList(comment);
    }

    @Override
    public int insertComment(Comment comment) {
        comment.setTime(DateUtil.now());
        commentMapper.insertComment(comment);

        Long id = comment.getId();
        // 更新root_id
        if (comment.getPid() == null) {
            comment.setRootId(id);
        } else {
            Comment parentComment = commentMapper.selectCommentById(comment.getPid());
            comment.setRootId(parentComment.getRootId());
        }
        return this.updateComment(comment);
    }

    @Override
    public int updateComment(Comment comment) {
        return commentMapper.updateComment(comment);
    }

    @Override
    public int deleteCommentByIds(Long[] ids) {
        return commentMapper.deleteCommentByIds(ids);
    }

    @Override
    public int deleteCommentById(Long id) {
        return commentMapper.deleteCommentById(id);
    }
}
